package com.viethp.mt.activities;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.google.android.c2dm.C2DMessaging;
import com.viethp.mt.activities.R;
import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.common.MyLocationListener;
import com.viethp.mt.objects.Position;
import com.viethp.mt.objects.SignUpResponse;
import com.viethp.mt.objects.User;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class ASignupScreen extends Activity implements OnClickListener {

	private Button btn_signup, btn_back;
	private EditText edt_username, edt_password, edt_confirm_password,
			edt_email, edt_phone;
	private String username, password, confirm_password, email, phone;

	private ProgressDialog progressDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_signup_screen);
		C2DMessaging.register(this, "aki@hirevietnamese.com");
		initComponents();
		setOnClickListener();
		setPosition();
	}

	public void initComponents() {
		btn_signup = (Button) findViewById(R.id.btn_signup);
		btn_back = (Button) findViewById(R.id.btn_back);

		edt_username = (EditText) findViewById(R.id.edt_username);
		edt_password = (EditText) findViewById(R.id.edt_password);
		edt_confirm_password = (EditText) findViewById(R.id.edt_confirm_password);
		edt_email = (EditText) findViewById(R.id.edt_email);
		edt_phone = (EditText) findViewById(R.id.edt_phone);

		progressDialog = new ProgressDialog(ASignupScreen.this);
		progressDialog.setCancelable(false);
	}

	public void setOnClickListener() {
		btn_signup.setOnClickListener(this);
		btn_back.setOnClickListener(this);
	}

	public void getInputText() {
		this.username = edt_username.getText().toString().trim();
		this.password = edt_password.getText().toString().trim();
		this.confirm_password = edt_confirm_password.getText().toString()
				.trim();
		this.email = edt_email.getText().toString().trim();
		this.phone = edt_phone.getText().toString().trim();
	}

	public boolean validInput() {
		getInputText();
		if (this.username.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Username is required.");
			edt_username.requestFocus();
			return false;
		} else if (this.password.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Password is required.");
			edt_password.requestFocus();
			return false;
		} else if (this.confirm_password.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Confirm password is required.");
			edt_confirm_password.requestFocus();
			return false;
		} else if (!this.confirm_password.equals(password)) {
			CommonHelper.showToast(getApplicationContext(),
					"Password doesn't match.");
			edt_password.requestFocus();
			return false;
		} else if (this.email.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Email is required.");
			edt_email.requestFocus();
			return false;
		} else if (!CommonHelper.eMailValidation(this.email)) {
			CommonHelper.showToast(getApplicationContext(),
					"Invalid email address.");
			edt_email.requestFocus();
			return false;
		} else if (this.phone.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Phone is required.");
			edt_phone.requestFocus();
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_signup:
			if (validInput()) {
				if (!CommonHelper.eMailValidation(this.email)) {
					edt_email.requestFocus();
					CommonHelper.showWarning(this,
							getString(R.string.emailvalid));
				} else {
					if (CommonHelper.isNetworkAvailable(this)) {
						startCallService();
					} else {
						CommonHelper.showWarning(ASignupScreen.this,
								getString(R.string.netstate));
					}
				}
			}
			break;
		case R.id.btn_back:
			this.finish();
		default:
			break;
		}

	}

	private void startCallService() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callService();
				handler.sendMessage(message);

			}
		}).start();
	}

	private SignUpResponse callService() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_REGISTER);
		userRequest.addProperty("username", this.username);
		userRequest.addProperty("email", this.email);
		userRequest.addProperty("phone", this.phone);
		String device_token = C2DMessaging
				.getRegistrationId(ASignupScreen.this);
		if (device_token.equals("")) {
			C2DMessaging.register(this, "aki@hirevietnamese.com");
			device_token = C2DMessaging.getRegistrationId(ASignupScreen.this);
			if (device_token.equals(""))
				device_token = "cantgetdevicetoken";
			else
				userRequest.addProperty("device_token", device_token);
		} else
			userRequest.addProperty("device_token", device_token);
		String md5Pass = CommonHelper.toMD5(this.password);
		userRequest.addProperty("password", md5Pass);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_REGISTER);
		request.addProperty(GlobalVariables.WS_METHOD_REGISTER, userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_REGISTER, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_REGISTER, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}
		return new SignUpResponse(results);

	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				SignUpResponse response = (SignUpResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(ASignupScreen.this, response
							.getErrorCode().getErrMsg());
				} else {
					User user = new User();
					user.setId(response.getUser_id());
					user.setUserName(username);
					user.setEmail(email);
					user.setPhone(phone);
					user.setPassWord(CommonHelper.toMD5(password.toString()));
					CommonHelper.setLoginMethod(GlobalVariables.LOGIN_BY_AA,
							ASignupScreen.this);
					CommonHelper.setNewReg(true, ASignupScreen.this);
					CommonHelper.setUserLogin(user, ASignupScreen.this);
					Intent intent = getIntent();
					setResult(RESULT_OK, intent);
					finish();
				}

			} else {
				CommonHelper.showWarning(ASignupScreen.this,
						getString(R.string.disconnect));
			}

		};
	};

	// position
	public void setPosition() {
		LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location loc = mlocManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		LocationListener mlocListener = new MyLocationListener(
				ASignupScreen.this);

		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);
		if (loc != null) {
			Position pos = new Position();
			pos.setLon(String.valueOf(loc.getLongitude()));
			pos.setLat(String.valueOf(loc.getLatitude()));
			CommonHelper.setPosition(pos, this);
			// CommonHelper.showToast(this, ""
			// + CommonHelper.getPosition(this).getLon() + " "
			// + CommonHelper.getPosition(this).getLat());
			Log.d("LastKnowLocation", ""
					+ CommonHelper.getPosition(this).getLon() + " "
					+ CommonHelper.getPosition(this).getLat());
		} 
		// else {
		// Position pos = new Position();
		// pos.setLon(String.valueOf(GlobalVariables.lon));
		// pos.setLat(String.valueOf(GlobalVariables.lat));
		// CommonHelper.setPosition(pos, this);
		// CommonHelper.showToast(this, ""
		// + CommonHelper.getPosition(this).getLon() + " "
		// + CommonHelper.getPosition(this).getLat());
		// }
	}
}
